package me.zxk.smartagriculture.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import me.zxk.smartagriculture.common.ApiResponse;
import me.zxk.smartagriculture.dto.note.NoteRequest;
import me.zxk.smartagriculture.dto.note.NoteResponse;
import me.zxk.smartagriculture.service.NoteService;
import me.zxk.smartagriculture.util.JwtUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 便签控制器
 */
@Tag(name = "便签管理", description = "便签的增删改查API")
@RestController
@RequestMapping("/api/notes")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
public class NoteController {

    private final NoteService noteService;
    private final JwtUtil jwtUtil;

    /**
     * 获取便签列表
     */
    @Operation(summary = "获取便签列表", description = "分页获取当前用户的便签列表，支持关键词搜索")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping
    public ApiResponse<Page<NoteResponse>> getNotesList(
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "updateTime,desc") String sort,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            
            // 解析排序参数
            String[] sortParams = sort.split(",");
            Sort.Direction direction = sortParams.length > 1 && "asc".equalsIgnoreCase(sortParams[1]) 
                    ? Sort.Direction.ASC : Sort.Direction.DESC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortParams[0]));
            
            Page<NoteResponse> notes = noteService.getUserNotes(userId, keyword, pageable);
            return ApiResponse.success(notes);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 获取便签详情
     */
    @Operation(summary = "获取便签详情", description = "根据ID获取便签详情")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "便签不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{id}")
    public ApiResponse<NoteResponse> getNoteDetail(
            @Parameter(description = "便签ID") @PathVariable Long id,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            NoteResponse note = noteService.getNoteDetail(id, userId);
            return ApiResponse.success(note);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 创建便签
     */
    @Operation(summary = "创建便签", description = "创建新的便签")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "创建成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "请求参数错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PostMapping
    public ApiResponse<NoteResponse> createNote(
            @Valid @RequestBody NoteRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            NoteResponse note = noteService.createNote(userId, request);
            return ApiResponse.success("便签创建成功", note);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 更新便签
     */
    @Operation(summary = "更新便签", description = "更新指定ID的便签")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "更新成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "便签不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PutMapping("/{id}")
    public ApiResponse<NoteResponse> updateNote(
            @Parameter(description = "便签ID") @PathVariable Long id,
            @Valid @RequestBody NoteRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            NoteResponse note = noteService.updateNote(id, userId, request);
            return ApiResponse.success("便签更新成功", note);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 删除便签
     */
    @Operation(summary = "删除便签", description = "删除指定ID的便签")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "删除成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "便签不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteNote(
            @Parameter(description = "便签ID") @PathVariable Long id,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            noteService.deleteNote(id, userId);
            return ApiResponse.success("便签删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 批量删除便签
     */
    @Operation(summary = "批量删除便签", description = "批量删除指定ID的便签")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "删除成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "请求参数错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @DeleteMapping
    public ApiResponse<Void> batchDeleteNotes(
            @Parameter(description = "便签ID列表") @RequestParam List<Long> ids,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            noteService.batchDeleteNotes(userId, ids);
            return ApiResponse.success("便签批量删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = extractTokenFromRequest(request);
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
